package drds.plus.repository.mysql.execute_plan_to_sql;

import drds.plus.common.jdbc.SetParameterMethodAndArgs;
import lombok.Getter;
import lombok.Setter;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * 一条需要执行的sql
 */
public class Sql {

    /**
     * 执行的sql
     */
    @Setter
    @Getter
    private String sql;
    /**
     * 绑定变量
     */
    @Setter
    @Getter
    private Map<Integer, SetParameterMethodAndArgs> indexToSetParameterMethodAndArgsMap;

    public boolean equals(Object o) {
        return indexToSetParameterMethodAndArgsMap.equals(o);
    }

    public int hashCode() {
        return indexToSetParameterMethodAndArgsMap.hashCode();
    }

    public String toString() {
        final int maxLen = 10;
        StringBuilder sb = new StringBuilder();
        if (sql != null) {
            sb.append(sql);
        }
        // 非空判断
        if (indexToSetParameterMethodAndArgsMap != null && !indexToSetParameterMethodAndArgsMap.isEmpty())
            sb.append(toString(indexToSetParameterMethodAndArgsMap.entrySet(), maxLen));

        sb.append("\n");
        return sb.toString();
    }

    private String toString(Collection<?> collection, int maxLen) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        int i = 0;
        for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {
            if (i > 0)
                sb.append(", ");
            sb.append(iterator.next());
        }
        sb.append("]");
        return sb.toString();
    }


}
